package com.qr.controller;


import com.qr.pojo.Loan;
import com.qr.service.LoanService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping(value = "/loan")
public class LoanController {
    @Resource
    private LoanService loanService;

    @RequestMapping("/allLoan")
    public String list(Model model) {
        List<Loan> list = loanService.findAll();
        model.addAttribute("list", list);
        return "allLoan";
    }
    @RequestMapping(value = "/toAddLoan")
    public String toaddLoan(){
        return "addLoan";
    }
    @RequestMapping(value = "/addLoan")
    public String addLoan(HttpServletRequest request, Model model){
        Loan loan = new Loan();
        loan.setSno(request.getParameter("sno"));
        loan.setISBN(request.getParameter("ISBN"));
        String borrowdate = request.getParameter("borrowdate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-mm-dd");
        try{
            Date date = simpleDateFormat.parse(borrowdate);
            loan.setBorrowdate(date);
        }catch (ParseException e){
            e.printStackTrace();
        }
        loanService.insert(loan);
        List<Loan> list = loanService.findAll();
        model.addAttribute("list", list);
        return "allLoan";
    }
    @RequestMapping(value = "/deleteLoan")
    public String todelete(String sno,String ISBN,Model model){
        loanService.deleteByPrimaryKey(sno,ISBN);
        List<Loan> list = loanService.findAll();
        model.addAttribute("list", list);
        return "allLoan";
    }
    @RequestMapping(value = "/toUpdate")
    public String toupdatepage(String sno,String ISBN, ModelMap model){
        Loan loan = loanService.selectByPrimaryKey(sno,ISBN);
        model.addAttribute("QLoan",loan);
        return "updateLoan";
    }
    @RequestMapping(value = "/updateLoan")
    public String doUpdate(HttpServletRequest request,Model model){
        Loan loan = new Loan();
        String borrowdate = request.getParameter("borrowdate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-mm-dd");
        try{
            Date date = simpleDateFormat.parse(borrowdate);
            loan.setBorrowdate(date);
        }catch (ParseException e){
            e.printStackTrace();
        }
        loanService.updateByPrimaryKey(loan);
        List<Loan> list = loanService.findAll();
        model.addAttribute("list", list);
        return "allLoan";
    }
}
